<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" class="login-form" auto-complete="on" label-position="left">
      <div class="title-container">
        <img width="180" src="https://cdn.boblog.com/FieFyVleQaVrqewVfPFkYgjlODZK" alt="logo">
      </div>

      <el-form-item prop="email">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input v-model="loginForm.phone" placeholder="phone" name="email" type="text" tabindex="1"
          auto-complete="on" />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
          placeholder="Password" name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <!-- 验证码输入区域 -->
      <el-form-item prop="captcha">
        <div class="captcha-input-container">
          <el-input
            v-model="captcha"
            placeholder="请输入验证码"
            style="flex: 1"
            @keyup.enter.native="handleLogin">
          </el-input>
          <div class="captcha-image" @click="refreshCaptcha">
            <canvas ref="captchaCanvas" width="120" height="40"></canvas>
          </div>
        </div>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import userApi from '@/plugins/api/user'
import { userCaozuo, updateSelf } from '@/plugins/utils/caozuojilu'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        phone: '15840930006',
        password: '',
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      captchaText: '151s', // 初始验证码设为图片中的BMZ
      captcha: ''
    }
  },
  mounted() {
    this.generateCaptcha();
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    // 生成验证码图片
    generateCaptcha() {
      const canvas = this.$refs.captchaCanvas;
      const ctx = canvas.getContext('2d');
      
      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      // 设置背景色（浅灰色）
      ctx.fillStyle = '#f5f7fa';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      // 绘制验证码文本（彩色）
      for (let i = 0; i < this.captchaText.length; i++) {
        ctx.fillStyle = this.getRandomColor();
        ctx.font = 'bold 24px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(
          this.captchaText[i],
          20 + i * 25,
          20,
        );
      }
    },
    
    // 获取随机颜色
    getRandomColor() {
      const colors = ['#FF5252', '#FF4081', '#E040FB', '#7C4DFF', '#536DFE', '#448AFF', '#40C4FF', '#18FFFF', '#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41', '#FFFF00', '#FFD740', '#FFAB40', '#FF6E40'];
      return colors[Math.floor(Math.random() * colors.length)];
    },
    
    // 刷新验证码
    refreshCaptcha() {
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      this.captchaText = '';
      for (let i = 0; i < 4; i++) {
        this.captchaText += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.generateCaptcha();
    },

    // 登录
    async handleLogin() {
      if (!this.loginForm.phone || !this.loginForm.password) {
        this.$message.error('请输入手机号和密码');
        return;
      }
      
      // 验证码校验
      if (!this.captcha) {
        this.$message.error('请输入验证码');
        return;
      }
      
      if (this.captcha.toUpperCase() !== this.captchaText) {
        this.$message.error('验证码不正确');
        this.refreshCaptcha();
        return;
      }

      console.log(this.loginForm);
      
      const obj = {
        phone: this.loginForm.phone,
        password: this.loginForm.password
      }
      
      const res = await userApi.login(obj)
      if (res.code === 200) {
        const user = res.data
        if (user.role > 2) {
          localStorage.setItem('user', JSON.stringify(res.data))
          this.$global.updateUser(res.data)
          await userCaozuo.login()
          this.$router.push('/')
        } else {
          this.$message.error('无权限使用该后台系统')
        }
      } else {
        this.$message.error(res.msg)
      }
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}

/* 验证码输入区域样式 */
.captcha-input-container {
  display: flex;
  align-items: center;
  width: 100%;
  
  .el-input {
    width: auto;
    flex: 1;
  }
  
  .captcha-image {
    margin-left: 10px;
    cursor: pointer;
    height: 47px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    
    canvas {
      width: 120px;
      height: 40px;
    }
    
    &:hover {
      opacity: 0.8;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    display: flex;
    align-items: center;
    height: 64px;
    margin-bottom: 32px;
    justify-content: center;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>